<?php

use support\utils\Cache;
use support\utils\JwtAuth;
use app\admin\logic\system\SystemConfigLogic;
use exception\ApiException;
use support\Response;
use Webman\Route;


/**
 * 快速注册路由[index|save|update|read|changeStatus|destroy|recycle|recovery|import|export]
 * @param string $name
 * @param string $controller
 * @return void
 */
function fastRoute(string $name, string $controller)
{
    $name = trim($name, '/');
    if (method_exists($controller, 'index')) Route::get("/$name/index", [$controller, 'index']);
    if (method_exists($controller, 'save')) Route::post("/$name/save", [$controller, 'save']);
    if (method_exists($controller, 'update')) Route::put("/$name/update/{id}", [$controller, 'update']);
    if (method_exists($controller, 'read')) Route::get("/$name/read/{id}", [$controller, 'read']);
    if (method_exists($controller, 'changeStatus')) Route::post("/$name/changeStatus", [$controller, 'changeStatus']);
    if (method_exists($controller, 'destroy')) Route::delete("/$name/destroy", [$controller, 'destroy']);
    if (method_exists($controller, 'recycle')) Route::get("/$name/recycle", [$controller, 'recycle']);
    if (method_exists($controller, 'realDestroy')) Route::delete("/$name/realDestroy", [$controller, 'realDestroy']);
    if (method_exists($controller, 'recovery')) Route::post("/$name/recovery", [$controller, 'recovery']);
    if (method_exists($controller, 'import')) Route::post("/$name/import", [$controller, 'import']);
    if (method_exists($controller, 'export')) Route::post("/$name/export", [$controller, 'export']);
}

/**
 * 快速注册常规路由[index|save|update|read|changeStatus|destroy|recycle|recovery|import|export]
 * @param string $name
 * @param string $controller
 * @return void
 */
function fastNormalRoute(string $name, string $controller)
{
    $name = trim($name, '/');
    if (method_exists($controller, 'index')) Route::get("/$name/index", [$controller, 'index']);
    if (method_exists($controller, 'save')) Route::post("/$name/save", [$controller, 'save']);
    if (method_exists($controller, 'update')) Route::put("/$name/update", [$controller, 'update']);
    if (method_exists($controller, 'read')) Route::get("/$name/read", [$controller, 'read']);
    if (method_exists($controller, 'changeStatus')) Route::post("/$name/changeStatus", [$controller, 'changeStatus']);
    if (method_exists($controller, 'destroy')) Route::delete("/$name/destroy", [$controller, 'destroy']);
    if (method_exists($controller, 'recycle')) Route::get("/$name/recycle", [$controller, 'recycle']);
    if (method_exists($controller, 'realDestroy')) Route::delete("/$name/realDestroy", [$controller, 'realDestroy']);
    if (method_exists($controller, 'recovery')) Route::post("/$name/recovery", [$controller, 'recovery']);
    if (method_exists($controller, 'import')) Route::post("/$name/import", [$controller, 'import']);
    if (method_exists($controller, 'export')) Route::post("/$name/export", [$controller, 'export']);
}

/**
 * 下载模板
 * @param $file_name
 * @return Response|\Webman\Http\Response
 */
function downloadFile($file_name)
{
    $base_dir = config('plugin.genadmin.Genadmin.template',base_path().'/public/template');
    if (file_exists($base_dir. DIRECTORY_SEPARATOR.$file_name)) {
        return response()->download($base_dir. DIRECTORY_SEPARATOR.$file_name, urlencode($file_name));
    } else {
        throw new ApiException('模板不存在');
    }
}

/**
 * 根据字节计算大小
 * @param $bytes
 * @return string
 */
function formatBytes($bytes): string
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    for ($i = 0; $bytes > 1024; $i++) {
        $bytes /= 1024;
    }
    return round($bytes, 2) . ' ' . $units[$i];
}

/**
 * 读取配置组
 * @param $group
 * @return bool|mixed
 */
function getConfigGroup($group)
{
    $logic = new SystemConfigLogic();
    return $logic->getGroup($group);
}

/**
 * 注册远程vue文件读取路由
 * @param string $plugin 插件名称
 * @param string $path 内部文件路径
 * @param bool $is_group 是否在分组路由内部
 * @return void
 */
function remoteVue(string $plugin, string $path, bool $is_group = true)
{
    Route::get(($is_group ? "" : "/$plugin") . $path, function () use ($plugin, $path) {
        $path = base_path().'/plugin/'.$plugin.'/remote'.$path;
        if (file_exists($path)) {
            return response()->file($path);
        } else {
            return response('Not Found', 404);
        }
    });
}



    /**
     * 生成订单号
     * @param string $prefix 订单前缀
     * @return string
     */
function generateOrderNo($prefix = '')
{
    // 获取毫秒级时间戳
    list($msec, $sec) = explode(' ', microtime());
    $msec = substr($msec, 2, 3);
    // 组合订单号（时间戳+毫秒+随机数）
    return $prefix . date('YmdHis') . $msec . mt_rand(100, 999);
}



/**
 * 补全URL链接
 */
function getUrlAttr($value)
{
    // 检查是否包含协议头
    if (preg_match('@^https?://@i', $value)) {
        return $value;
    }

    if (preg_match('@^/oss/@iUs', $value)) {
        $storage = (new SystemConfigLogic())->getConfig("storage")['value'];
        if (!empty($storage['engine'][$storage['default']]['config'])) {
            return $storage['engine'][$storage['default']]['config']['domain'] . $value;
        }
        return "//" . request()->host(true) . $value;
    } else {
        return "//" . request()->host(true) . $value;
    }
}

/**
 * 转化字符串到证书中
 * @param $rsaStr
 * @return false|string
 * @throws Exception
 */
function convert_str_to_pem($rsaStr)
{
    $filePath = runtime_path() . '/cert' . DIRECTORY_SEPARATOR . md5($rsaStr) . '.pem';
    if (file_exists($filePath)) {
        return realpath($filePath);
    }
    if (!file_exists(dirname($filePath))) {
        mkdir(dirname($filePath), 0755, true);//创建临时目录
    }
    @file_put_contents($filePath, $rsaStr);
    return realpath($filePath);
}

/**
 * 写入日志
 * @param string|array $values
 * @param string $dir
 * @return bool|int
 */
function write_log($values, $dir)
{
    if (is_array($values))
        $values = print_r($values, true);
    // 日志内容
    $content = '[' . date('Y-m-d H:i:s') . ']' . PHP_EOL . $values . PHP_EOL . PHP_EOL;
    try {
        // 文件路径
        $filePath = $dir . '/';
        // 路径不存在则创建
        !is_dir($filePath) && mkdir($filePath, 0755, true);
        // 写入文件
        return file_put_contents($filePath . date('Ymd') . '.log', $content, FILE_APPEND);
    } catch (\Exception $e) {
        return false;
    }
}
